/*
 * tileCache.java
 *
 * Copyright (C) 2008 Paul Nettleship
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 */
package staticTrailExplorer;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;

/**
 *
 * @author codebauer
 */
public class tileCache
   {     
   private ArrayList storageArea = new ArrayList();
   private UIActions UIController;
   private String fileCacheDir;
   private static final int maxArraySize = 100;
   private static final int thrashSize = 100;
   
   public tileCache( UIActions UIController )
      {
      this.UIController = UIController;

      String dir = "." + File.separatorChar + "filecache" + File.separatorChar;
      if (new File(dir).isDirectory() != true)
         {
         String text = "Can not find  " + dir + " dir.\n";
         text += "Disabling file cache";
         JOptionPane.showMessageDialog(null, text, "Warning", JOptionPane.PLAIN_MESSAGE);
         fileCacheDir = null;
         }
      else
         {
         fileCacheDir = dir;
         }
      }

   public BufferedImage get(tileMap map, location loc, boolean blocking)
      {
      tile element;
      String locName = loc.getName(map);

      /* Try mem cache */
      for (int i = 0; i < storageArea.size(); i++)
         {
         element = (tile) storageArea.get(i);
         if (locName.equals(element.name))
            {
            /* To prevent constant re-ordering of current displayed tiles
               consider first x in list to be new, i.e. Don't move to head */
            if( i > thrashSize )
               {
               storageArea.remove(i);
               storageArea.add(0, element);
               }
            return element.getImage();
            }
         }

      /* Try file cache */
         if (fileCacheDir != null)
            {
            File phile = new File(fileCacheDir + locName);
            if (phile.exists())
               {
               try
                  {
                  element = new tile(locName);
                  storageArea.add(0, element);
                  element.setImage(ImageIO.read(phile));
                  return element.getImage();
                  }
               catch (IOException ex)
                  {
                  System.out.print(ex);
                  }
               }
            }

      /* cache miss */
      element = new tile(locName);
      storageArea.add(0, element);

      if( blocking == false)
         {
         (new Thread(new cacheLoadThread(map, loc, element) )).start();
         }
      else
         {
         dowloadTile(element, map, loc);
         }
      cacheClean();
      return element.getImage();
      }

   /* Clean out old entries */
   private void cacheClean()
      {
      while( storageArea.size() > maxArraySize )
         storageArea.remove(storageArea.size()-1);
      }

   private class cacheLoadThread implements Runnable
      {
      private tileMap map;
      private location loc;
      private tile element;

      public cacheLoadThread(tileMap map, location loc, tile element)
         {
         this.map = map;
         this.loc = loc;
         this.element = element;
         }

      public void run()
         {
         dowloadTile(element, map, loc);
        }
      }

   private void dowloadTile(tile element, tileMap map, location loc)
      {
      try
         {
         BufferedImage image = map.getMapData().loadMapTile(loc);
         element.setImage(image);
         UIController.repaintAll();
         if ((image != null) && (fileCacheDir!=null))
            ImageIO.write(image, "png", new File(fileCacheDir + element.name));
         System.out.print("cacheMiss:" + loc.getName(map) + "\n");
         }
      catch (IOException ex)
         {
         System.out.print( ex);
         }
      }

}

